﻿using System;
using System.Collections.Generic;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Net;
using System.Text;
using System.Threading.Tasks;
using System.Web.Helpers;
using System.Web.Mvc;
using System.Web.Security;
using StockMatch.Service;

namespace StockMatch.WebSite
{
    public static class CommonFunc
    {
        #region 定义下拉列表项

        public static Dictionary<int, string> EducationList = new Dictionary<int, string>()
        {
            {1,"硕士"},
            {2,"大学"},
            {3,"中专"},
            {4,"高中"},
            {5,"初中"},
            {6,"小学"},
            {7,"其他"}
        };

        public static Dictionary<int, string> IndustryList = new Dictionary<int, string>()
        {
            {1,"金融业"},
            {2,"服务业"},
            {3,"信息产业"},
            {4,"制造业"},
            {5,"传播业"},
            {6,"教育"},
            {7,"政府机构"},
            {8,"医疗保健"},
            {9,"房地产"},
            {10,"其他"}
        };


        public static Dictionary<int, string> PositionList = new Dictionary<int, string>()
        {
            {1,"学生"},
            {2,"职员"},
            {3,"经理"},
            {4,"专业人士"},
            {5,"公务员"},
            {6,"私营主"},
            {7,"待业"},
            {8,"退休"},
            {9,"其他"}
        };


        public static Dictionary<int, string> MonthlySalaryList = new Dictionary<int, string>()
        {
            {1,"6000以上"},
            {2,"4001-6000"},
            {3,"2001-4000"},
            {4,"1001-2000"},
            {5,"501-1000"},
            {6,"500以下"}
        };

        #endregion

        #region 生成下拉列表

        #region 学历下拉列表
        
        /// <summary>
        /// 学历下拉列表
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public static IEnumerable<SelectListItem> GetEducationDropdown(int? id)
        {
            List<SelectListItem> droplist = new List<SelectListItem>();
            droplist.Add(new SelectListItem(){Text = "请选择",Value ="0" });
            foreach (var item in EducationList)
            {
                droplist.Add(new SelectListItem(){Text =item.Value,Value = item.Key.ToString(),Selected =(id==item.Key)});
            }
            return droplist as IEnumerable<SelectListItem>;
        }

        #endregion 学历下拉列表

        #region 行业下拉列表

        /// <summary>
        /// 行业下拉列表
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public static IEnumerable<SelectListItem> GetIndustryDropdown(int? id)
        {
            List<SelectListItem> droplist = new List<SelectListItem>();
            droplist.Add(new SelectListItem() { Text = "请选择", Value = "0" });
            foreach (var item in IndustryList)
            {
                droplist.Add(new SelectListItem() { Text = item.Value, Value = item.Key.ToString(), Selected = (id == item.Key) });
            }
            return droplist as IEnumerable<SelectListItem>;
        }

        #endregion 行业下拉列表
        
        #region 职业下拉列表

        /// <summary>
        /// 职业下拉列表
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public static IEnumerable<SelectListItem> GetPositionDropdown(int? id)
        {
            List<SelectListItem> droplist = new List<SelectListItem>();
            droplist.Add(new SelectListItem() { Text = "请选择", Value = "0" });
            foreach (var item in PositionList)
            {
                droplist.Add(new SelectListItem() { Text = item.Value, Value = item.Key.ToString(), Selected = (id == item.Key) });
            }
            return droplist as IEnumerable<SelectListItem>;
        }

        #endregion 职业下拉列表


        #region 月收入下拉列表

        /// <summary>
        /// 月收入下拉列表
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public static IEnumerable<SelectListItem> GetMonthlySalaryDropdown(int? id)
        {
            List<SelectListItem> droplist = new List<SelectListItem>();
            droplist.Add(new SelectListItem() { Text = "请选择", Value = "0" });
            foreach (var item in MonthlySalaryList)
            {
                droplist.Add(new SelectListItem() { Text = item.Value, Value = item.Key.ToString(), Selected = (id == item.Key) });
            }
            return droplist as IEnumerable<SelectListItem>;
        }

        #endregion 月收入下拉列表

        #endregion

        #region 查询下拉列表值

        /// <summary>
        /// 学历
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public static string GetEducationText(int? id)
        {
            string text = "未填写";
            if (id > 0)
            {
                text = EducationList.First(c => c.Key == id).Value;
            }
            return text;
        }

        /// <summary>
        /// 行业
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public static string GetIndustryText(int? id)
        {
            string text = "未填写";
            if (id > 0)
            {
                text = IndustryList.First(c => c.Key == id).Value;
            }
            return text;
        }


        /// <summary>
        /// 职业
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public static string GetPositionText(int? id)
        {
            string text = "未填写";
            if (id > 0)
            {
                text = PositionList.First(c => c.Key == id).Value;
            }
            return text;
        }


        /// <summary>
        /// 月收入
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public static string GetMonthlySalaryText(int? id)
        {
            string text = "未填写";
            if (id > 0)
            {
                text = MonthlySalaryList.First(c => c.Key == id).Value;
            }
            return text;
        }

        /// <summary>
        /// 婚姻状态
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public static string GetIsMarriageText(int? id)
        {
            string text = "未填写";
            if (id > 0)
            {
                switch (id)
                {
                    case 1: text = "未婚"; break;
                    case 2: text = "已婚"; break;
                    case 3: text = "离异"; break;
                    case 4: text = "丧偶"; break;
                }
            }
            return text;
        }

        #endregion

        #region 计算时间差（天）

        public static int DateDiff(this DateTime dateTime1, DateTime dateTime2)
        {
            TimeSpan ts1 = new TimeSpan(dateTime1.Ticks);
            TimeSpan ts2 = new TimeSpan(dateTime2.Ticks);
            TimeSpan ts = ts1.Subtract(ts2).Duration();
            return ts.Days;
        }

        #endregion

        #region 获取方案的状态
        public static string GetProjectState(int projectState)
        {
            switch (projectState)
            {
                case 1:
                    return "验资中";
                case 3:
                    return "开户中";
                case 5:
                    return "操盘中";
                case 7:
                    return "亏损";
                case 9:
                    return "平仓";
                case 11:
                    return "终止操盘";
                case 13:
                    return "终止操盘";
                case 15:
                    return "已完结";
                default:
                    return "";
            }
        }
        #endregion

        #region 获取方案的状态详细
        public static string GetProjectStateDetail(int projectState)
        {
            switch (projectState)
            {
                case 1:
                    return "正在验资中";
                case 3:
                    return "正在开户中";
                case 5:
                    return "正在操盘中";
                case 7:
                    return "已亏损";
                case 9:
                    return "平仓";
                case 11:
                    return "终止操盘";
                case 13:
                    return "终止操盘";
                case 15:
                    return "方案已完结";
                default:
                    return "";
            }
        }

        #endregion

        #region 验证身份证号
        /// <summary>
       /// 身份证验证
       /// </summary>
       /// <param name="id">身份证号</param>
       /// <returns></returns>
       public static bool CheckIDCard(string id)
        {
            if (id.Length == 18)
           {
               return CheckIDCard18(id);
            }
            if (id.Length == 15)
            {
                return CheckIDCard15(id);
            }
            return false;
        }

        /// <summary>
        /// 18位身份证验证
        /// </summary>
        /// <param name="Id">身份证号</param>
        /// <returns></returns>
       private static bool CheckIDCard18(string Id)
        {
            long n = 0;
            if (long.TryParse(Id.Remove(17), out n) == false || n < Math.Pow(10, 16) || long.TryParse(Id.Replace('x', '0').Replace('X', '0'), out n) == false)
            {
                return false;//数字验证
            }
            const string address = "11x22x35x44x53x12x23x36x45x54x13x31x37x46x61x14x32x41x50x62x15x33x42x51x63x21x34x43x52x64x65x71x81x82x91";
            if (address.IndexOf(Id.Remove(2), StringComparison.Ordinal) == -1)
            {
                return false;//省份验证
            }
            string birth = Id.Substring(6, 8).Insert(6, "-").Insert(4, "-");
            DateTime time = new DateTime();
            if (DateTime.TryParse(birth, out time) == false)
            {
                return false;//生日验证
            }
            string[] arrVarifyCode = ("1,0,x,9,8,7,6,5,4,3,2").Split(',');
            string[] Wi = ("7,9,10,5,8,4,2,1,6,3,7,9,10,5,8,4,2").Split(',');
            char[] Ai = Id.Remove(17).ToCharArray();
            int sum = 0;
            for (int i = 0; i < 17; i++)
            {
                sum += int.Parse(Wi[i]) * int.Parse(Ai[i].ToString());
            }
            int y = -1;
            Math.DivRem(sum, 11, out y);
            if (arrVarifyCode[y] != Id.Substring(17, 1).ToLower())
            {
                return false;//校验码验证
            }
            return true;//符合GB11643-1999标准
        }
        /// <summary>
        /// 15位身份证验证
        /// </summary>
        /// <param name="id">身份证号</param>
        /// <returns></returns>
        private static bool CheckIDCard15(string id)
        {
            long n = 0;
            if (long.TryParse(id, out n) == false || n < Math.Pow(10, 14))
            {
                return false;//数字验证
            }
            const string address = "11x22x35x44x53x12x23x36x45x54x13x31x37x46x61x14x32x41x50x62x15x33x42x51x63x21x34x43x52x64x65x71x81x82x91";
            if (address.IndexOf(id.Remove(2), StringComparison.Ordinal) == -1)
            {
                return false;//省份验证
            }
            string birth = id.Substring(6, 6).Insert(4, "-").Insert(2, "-");
            DateTime time = new DateTime();
            if (DateTime.TryParse(birth, out time) == false)
            {
                return false;//生日验证
            }
            return true;//符合15位身份证标准
        }
        #endregion

        #region 格式化
        public static string MoneyFormat(this decimal money)
        {
            if (money < 1000)
            {
                return money.ToString(CultureInfo.InvariantCulture);
            }
            return money.ToString("#,###");
        }
        public static string MoneyFormat(this int money)
        {
            return money.ToString("#,###");
        }

        public static string HideFormat(this string str,int start,int end)
        {
            if (string.IsNullOrEmpty(str))
            {
                return string.Empty;
            }
            StringBuilder sb=new StringBuilder();
            int i = 0;
            foreach (char s in str)
            {
                if (i >= start && i < str.Length-end)
                {
                    sb.Append('*');
                }
                else
                {
                    sb.Append(s);
                }
                i++;
            }
            return sb.ToString();
        }
        public static string HideFormat(this string str, int start, char end)
        {
            if (string.IsNullOrEmpty(str))
            {
                return string.Empty;
            }
            StringBuilder sb = new StringBuilder();
            int i = 0;
            foreach (char s in str)
            {
                if (i >= start && i < str.IndexOf(end))
                {
                    sb.Append('*');
                }
                else
                {
                    sb.Append(s);
                }
                i++;
            }
            return sb.ToString();
        }

        #endregion

        public static string RandomCode()
        {
            Random random = new Random();
            return random.Next(0, 9999).ToString();
        }

        #region 短信接口

        public static string SendLockCode(string phone)
        {
            string sendurl = WebConfig.MessageInterfaceUrl;
            string mobile = phone; //发送号码

            string result = RandomCode();

            string strContent = "您好，您在【" + WebConfig.WebSiteName + "】注册的短信验证码是" + result;

            StringBuilder sbTemp = new StringBuilder();
            string uid = WebConfig.MessageInterfaceUserName;
            string pwd = WebConfig.MessageInterfaceUserPassword;
            string Pass = FormsAuthentication.HashPasswordForStoringInConfigFile(pwd + uid, "MD5"); //密码进行MD5加密
            //POST 传值
            sbTemp.Append("uid=" + uid + "&pwd=" + Pass + "&mobile=" + mobile + "&content=" + strContent);
            byte[] bTemp = System.Text.Encoding.GetEncoding("GBK").GetBytes(sbTemp.ToString());
            String postReturn = DoPostRequest(sendurl, bTemp);
            Logger.Info(strContent);
            return result; //返回验证码
        }

        private static String DoPostRequest(string url, byte[] bData)
        {
            System.Net.HttpWebRequest hwRequest;
            System.Net.HttpWebResponse hwResponse;

            string strResult = string.Empty;
            try
            {
                hwRequest = (System.Net.HttpWebRequest) System.Net.WebRequest.Create(url);
                hwRequest.Timeout = 5000;
                hwRequest.Method = "POST";
                hwRequest.ContentType = "application/x-www-form-urlencoded";
                hwRequest.ContentLength = bData.Length;

                System.IO.Stream smWrite = hwRequest.GetRequestStream();
                smWrite.Write(bData, 0, bData.Length);
                smWrite.Close();
            }
            catch (System.Exception err)
            {
                Logger.Error(err.Message);
                return strResult;
            }

            //get response
            try
            {
                hwResponse = (HttpWebResponse)hwRequest.GetResponse();
                StreamReader srReader = new StreamReader(hwResponse.GetResponseStream(), Encoding.ASCII);
                strResult = srReader.ReadToEnd();
                srReader.Close();
                hwResponse.Close();
            }
            catch (System.Exception err)
            {
                Logger.Error(err.ToString());
            }
            return strResult;
        }

        #endregion

        #region 邮箱接口
        public static string SendEmail(string email)
        {
            string result = RandomCode();
            string strContent = "您好，您在【" + WebConfig.WebSiteName + "】的邮箱验证码是" + result;
            DotNetSendMail sendMail = new DotNetSendMail();
            bool sendResultFlag = sendMail.SendMail("zhaojingadmin@163.com", email, strContent, strContent, "smtp.163.com", "zhaojingadmin@163.com", "wenjunjing");
            if (sendResultFlag)
            {
                Logger.Info(strContent);
            }
            else
            {
                Logger.Error("邮件发送失败："+sendMail.SendMailResult);
            } 
            return result;
        }

        #endregion

        public static object Result(int code,string message)
        {
            return new { code = code, message = message };
        }
    }
}
